package com.fasteat.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


@Component
public class ChatNettyServer {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${netty.port}")
    private Integer port;

    //boss线程组，用于服务端接受客户端的连接
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    //worker 线程组，用于服务端接受客户端的数据读写
    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;

    /**
     * 启动sever
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)  // 指定 Channel 为服务端 NioServerSocketChannel
                .option(ChannelOption.SO_BACKLOG, 1024) // 服务端 accept 队列的大小
                .childOption(ChannelOption.SO_KEEPALIVE, true) // TCP Keepalive 机制，实现 TCP 层级的心跳保活功能
                .childOption(ChannelOption.TCP_NODELAY, true) // 高实时，TCP有数据发送时就马上发送
                .childHandler(new ChatServerInitializer());

        ChannelFuture future = bootstrap.bind(port).sync();
        if(future.isSuccess()){
            channel = future.channel();
            logger.info("Netty Server启动成功");
        }
    }

    /**
     * 关闭sever
     */
    @PreDestroy
    public void shutDown(){
        if(channel != null){
            channel.close();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
